package org.wj.problem;

import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MyAtoi {

	private static final int INT_MIN = Integer.MIN_VALUE;
	private static final int INT_MAX = Integer.MAX_VALUE;

	public static void main(String[] args) {
		int i = myAtoi("2147483648");
		System.out.println(i);
	}

	public static int myAtoi(String str) {
		Pattern numPattern = Pattern.compile("([+-]?)([0]*)([1-9]+[0-9]*)(.*)");
		Matcher matcher = numPattern.matcher(str.trim());
		if (matcher.find() && matcher.matches()) {
			String numSign = matcher.group(1);
			String num = matcher.group(3);
			String intMax = String.valueOf(INT_MAX);
			String intMin = String.valueOf(INT_MIN);
			if (numSign == null || numSign.isEmpty() || Objects.equals("+", numSign)) {
				if (num.length() > intMax.length() || (num.length() == intMax.length() && num.compareTo(intMax) >= 0)) {
					return INT_MAX;
				}
				return Integer.parseInt(num);
			}
			if (Objects.equals("-", numSign)) {
				num = numSign + num;
				if (num.length() > intMin.length() || (num.length() == intMin.length() && num.compareTo(intMin) > 0)) {
					return INT_MIN;
				}
				return Integer.parseInt(num);
			}
		}
		return 0;
	}
}
